<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
	<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
	<title>系统设置</title>
	<link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
	<style>
		body {}

		p {
			margin-bottom: 15px;
		}

		/* 优化搜索结果面板定位 */
		.aui-list-item-input {
			position: relative;
		}
	</style>
</head>

<body>
	<header class="aui-bar aui-bar-nav" style="background-color: #03a9f4">
		<a class="aui-pull-left aui-btn" onclick="closeWin()">
			<span class="aui-iconfont aui-icon-left"></span>
		</a>
		<div class="aui-title" style="padding-top: 10px;">
			<!-- <img src='../image/logo-smaller.png'/> -->
		</div>
	</header>

	<div class="aui-content aui-margin-b-15">
		<ul class="aui-list aui-form-list">
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">内网IP</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="IP地址" id="serverIp" value="192.168.10.204" />
					</div>
				</div>
			</li>
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">内网端口号</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="如8080" id="serverPort" value="8001" />
					</div>
				</div>
			</li>
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">内网服务名</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="服务器访问名称" id="serverProject" value="htsys" />
					</div>
				</div>
			</li>
		</ul>
	</div>

	<div class="aui-content aui-margin-b-15">
		<ul class="aui-list aui-form-list">
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">外网IP</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="IP地址" id="serverIpW" value="1.94.233.195" />
					</div>
				</div>
			</li>
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">外网端口号</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="如8080" id="serverPortW" value="8002" />
					</div>
				</div>
			</li>
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">外网服务名</div>
					<div class="aui-list-item-input">
						<input type="text" placeholder="服务器访问名称" id="serverProjectW" value="htsys" />
					</div>
				</div>
			</li>
		</ul>
	</div>

	<div class="aui-content aui-margin-b-15">
		<ul class="aui-list aui-form-list">
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">网络选择</div>
					<div class="aui-list-item-input">
						<label><input class="aui-radio" type="radio" id="inRadio" name="netRadio" checked value="in"
								onclick="doSelectNet()">内网</label>
						<label><input class="aui-radio" type="radio" id="outRadio" name="netRadio" value="out"
								onclick="doSelectNet()">外网</label>
					</div>
				</div>
			</li>
		</ul>
	</div>
	<div class="aui-content aui-margin-b-15">
		<ul class="aui-list aui-form-list">
			<li class="aui-list-item">
				<div class="aui-list-item-inner">
					<div class="aui-list-item-label">设备唯一号</div>
					<div class="aui-list-item-input">
						<!-- 输入框用于模糊查询 -->
						<input type="text" id="equipSearch" placeholder="请点击输入框搜索设备">
						<!-- 隐藏的下拉框用于存储所有选项 -->
						<select id="equipUniqueId" style="display: none;"></select>
						<!-- 用于展示匹配结果的下拉面板 -->
						<div id="searchResult" class="aui-list"
							style="position: absolute; z-index: 999; width: 100%; background: white; border: 1px solid #eee; max-height: 200px; overflow-y: auto; display: none;">
						</div>
					</div>
				</div>
			</li>
		</ul>
	</div>

	<div class="aui-content-padded">
		<p>
		<div class="aui-btn aui-btn-info aui-btn-block" onclick='pingTest()'>网络检测</div>
		</p>
	</div>

	<div class="aui-content-padded">
		<p>
		<div class="aui-btn aui-btn-success aui-btn-block" onclick='doSave()'>保存</div>
		</p>
	</div>

</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>

<script type="text/javascript">
	var equipUniqueId;
	var allOptions = []; // 存储所有设备选项数据

	apiready = function () {
		var serverIpN = localStorage.getItem('serverIpN');
		var serverPortN = localStorage.getItem('serverPortN');
		var serverProjectN = localStorage.getItem('serverProjectN');
		var serverIpW = localStorage.getItem('serverIpW');
		var serverPortW = localStorage.getItem('serverPortW');
		var serverProjectW = localStorage.getItem('serverProjectW');

		var netChoice = localStorage.getItem('netChoice');
		equipUniqueId = localStorage.getItem('equipUniqueId');

		if (serverIpN != null || serverPortN != null || serverProjectN != null) {
			$("#serverIp").val(serverIpN);
			$("#serverPort").val(serverPortN);
			$("#serverProject").val(serverProjectN);
		}

		if (serverIpW != null || serverPortW != null || serverProjectW != null) {
			$("#serverIpW").val(serverIpW);
			$("#serverPortW").val(serverPortW);
			$("#serverProjectW").val(serverProjectW);
		}

		if (netChoice != null && netChoice == "in") {
			document.getElementById('inRadio').checked = true;
			selectInNet();
		} else if (netChoice != null && netChoice == "out") {
			document.getElementById('outRadio').checked = true;
			selectOutNet();
		}
		// 初始化搜索功能
		initSearchFunction();
	};

	// 初始化搜索功能
	function initSearchFunction() {
		const searchInput = document.getElementById('equipSearch');
		const equipSelect = document.getElementById('equipUniqueId');
		const resultPanel = document.getElementById('searchResult');

		// 点击输入框时加载设备列表
		searchInput.addEventListener('click', function (e) {
			e.stopPropagation(); // 防止事件冒泡
			searchEquip(true); // 传入true表示需要显示结果面板
		});
		var equipSearchVal = $("#equipSearch").val()
		if (equipSearchVal == '' && equipUniqueId != null) {
			$("#equipSearch").val(equipUniqueId);
		}

		// 处理搜索逻辑
		searchInput.addEventListener('input', function () {
			const keyword = this.value.trim().toLowerCase();
			resultPanel.innerHTML = '';

			if (keyword) {
				// 过滤匹配的选项
				const matchedOptions = allOptions.filter(option =>
					option.text.toLowerCase().includes(keyword) ||
					option.value.toLowerCase().includes(keyword)
				);

				if (matchedOptions.length > 0) {
					// 显示匹配结果
					matchedOptions.forEach(option => {
						const item = document.createElement('div');
						item.className = 'aui-list-item';
						item.style.padding = '10px';
						item.style.cursor = 'pointer';
						item.innerHTML = option.text;
						item.dataset.value = option.value;

						// 点击选项时选中
						item.addEventListener('click', function () {
							searchInput.value = this.innerHTML;
							equipSelect.value = this.dataset.value;
							resultPanel.style.display = 'none';
						});

						resultPanel.appendChild(item);
					});
					resultPanel.style.display = 'block';
				} else {
					// 无匹配结果
					resultPanel.innerHTML = '<div class="aui-list-item" style="padding: 10px;">无匹配结果</div>';
					resultPanel.style.display = 'block';
				}
			} else {
				// 关键词为空时显示所有选项
				showAllOptions();
			}
		});

		// 点击页面其他地方隐藏结果面板
		document.addEventListener('click', function (e) {
			if (!searchInput.contains(e.target) && !resultPanel.contains(e.target)) {
				resultPanel.style.display = 'none';
			}
		});

		// 显示所有选项
		function showAllOptions() {
			resultPanel.innerHTML = '';
			if (allOptions.length > 0) {
				allOptions.forEach(option => {
					const item = document.createElement('div');
					item.className = 'aui-list-item';
					item.style.padding = '10px';
					item.style.cursor = 'pointer';
					item.innerHTML = option.text;
					item.dataset.value = option.value;

					item.addEventListener('click', function () {
						searchInput.value = this.innerHTML;
						equipSelect.value = this.dataset.value;
						resultPanel.style.display = 'none';
					});

					resultPanel.appendChild(item);
				});
				resultPanel.style.display = 'block';
			} else {
				resultPanel.innerHTML = '<div class="aui-list-item" style="padding: 10px;">暂无设备数据</div>';
				resultPanel.style.display = 'block';
			}
		}
	}

	// 搜索设备列表，showPanel参数控制是否显示结果面板
	function searchEquip(showPanel) {
		var un = localStorage.getItem('un');

		// 根据当前选中的网络获取服务器地址
		var serverIp, serverPort, serverProject;
		if (document.getElementById('inRadio').checked) {
			serverIp = $("#serverIp").val();
			serverPort = $("#serverPort").val();
			serverProject = $("#serverProject").val();
		} else {
			serverIp = $("#serverIpW").val();
			serverPort = $("#serverPortW").val();
			serverProject = $("#serverProjectW").val();
		}

		var serverUrl = "http://" + serverIp + ":" + serverPort + "/" + serverProject;

		var url = serverUrl + "/app/getSearchEquipSelectList";
		var data = {
			values: {
				un: un
			}
		};

		api.showProgress({
			title: '加载设备列表...'
		});

		api.ajax({
			url: url,
			method: 'post',
			dataType: 'json',
			timeout: 30,
			returnAll: false,
			data: data
		}, function (ret, err) {
			api.hideProgress();

			if (ret) {
				var map = ret;
				var list = map.list || [];

				// 更新隐藏的select选项
				var html = "<option value=''>--请选择--</option>";
				allOptions = []; // 清空现有数据

				for (var i = 0; i < list.length; i++) {
					var clientCode = list[i].clientCode || '';
					html += "<option value='" + clientCode + "'>" + clientCode + "</option>";
					allOptions.push({
						value: clientCode,
						text: clientCode
					});
				}

				$api.html($api.byId("equipUniqueId"), html);

				// 设置已保存的设备号
				if (equipUniqueId != null) {
					$("#equipUniqueId").val(equipUniqueId);
					// 同步到输入框
					const matched = allOptions.find(option => option.value === equipUniqueId);
					if (matched) {
						$("#equipSearch").val(matched.text);
					}
				}

				// 如果需要显示面板，则展示所有选项
				if (showPanel) {
					const resultPanel = document.getElementById('searchResult');
					resultPanel.innerHTML = '';

					if (allOptions.length > 0) {
						allOptions.forEach(option => {
							const item = document.createElement('div');
							item.className = 'aui-list-item';
							item.style.padding = '10px';
							item.style.cursor = 'pointer';
							item.innerHTML = option.text;
							item.dataset.value = option.value;

							item.addEventListener('click', function () {
								$("#equipSearch").val(this.innerHTML);
								$("#equipUniqueId").val(this.dataset.value);
								resultPanel.style.display = 'none';
							});

							resultPanel.appendChild(item);
						});
						resultPanel.style.display = 'block';
					} else {
						resultPanel.innerHTML = '<div class="aui-list-item" style="padding: 10px;">暂无设备数据</div>';
						resultPanel.style.display = 'block';
					}
				}
			} else {
				api.toast({
					msg: '设备列表加载失败',
					duration: 2000,
					location: 'middle'
				});
			}
		});
	}

	function closeWin() {
		api.closeWin();
		if (api.pageParam.name != null && api.pageParam.name != "" && api.pageParam.name != undefined) {
			api.execScript({
				name: api.pageParam.name,
				script: 'refresh()'
			});
		}
	}

	function doSelectNet() {
		var obj = document.getElementsByName('netRadio');
		for (var i = 0; i < obj.length; i++) {
			if (obj[i].checked == true) {
				if (obj[i].value == 'in') {
					selectInNet();
				} else if (obj[i].value == 'out') {
					selectOutNet();
				}
			}
		}
	}

	function selectInNet() {
		document.getElementById("serverIp").disabled = false;
		document.getElementById("serverPort").disabled = false;
		document.getElementById("serverProject").disabled = false;

		document.getElementById("serverIpW").disabled = true;
		document.getElementById("serverPortW").disabled = true;
		document.getElementById("serverProjectW").disabled = true;
	}

	function selectOutNet() {
		document.getElementById("serverIpW").disabled = false;
		document.getElementById("serverPortW").disabled = false;
		document.getElementById("serverProjectW").disabled = false;

		document.getElementById("serverIp").disabled = true;
		document.getElementById("serverPort").disabled = true;
		document.getElementById("serverProject").disabled = true;
	}

	function pingTest() {
		var obj = document.getElementsByName('netRadio');
		var serverIp = "";

		for (var i = 0; i < obj.length; i++) {
			if (obj[i].checked == true) {
				if (obj[i].value == 'in') {
					serverIp = $("#serverIp").val();
				} else if (obj[i].value == 'out') {
					serverIp = $("#serverIpW").val();
				}
			}
		}

		var modulePing = api.require('modulePing');
		api.showProgress({
			title: '网络检测中...'
		});
		modulePing.pingtest({
			ip: serverIp
		}, function (ret, err) {
			api.hideProgress();
			if (ret) {
				if (ret.okNum > 0) {
					api.toast({
						msg: '网络通畅'
					});
				} else {
					api.toast({
						msg: '网络不通'
					});
				}
			} else {
				alert(JSON.stringify(err));
			}
		});
	}

	function doCheck() {
		var obj = document.getElementsByName('netRadio');
		var serverIp = "";
		var serverPort = "";
		var serverProject = "";

		for (var i = 0; i < obj.length; i++) {
			if (obj[i].checked == true) {
				if (obj[i].value == 'in') {
					serverIp = $("#serverIp").val();
					serverPort = $("#serverPort").val();
					serverProject = $("#serverProject").val();
					if (serverIp != "" && serverPort != "" && serverProject != "") {
						checkNet(serverIp, serverPort, serverProject);
					} else {
						api.toast({
							msg: '请填写完整网络信息',
							duration: 2000,
							location: 'middle'
						});
					}
				} else if (obj[i].value == 'out') {
					serverIp = $("#serverIpW").val();
					serverPort = $("#serverPortW").val();
					serverProject = $("#serverProjectW").val();
					if (serverIp != "" && serverPort != "" && serverProject != "") {
						checkNet(serverIp, serverPort, serverProject);
					} else {
						api.toast({
							msg: '请填写完整网络信息',
							duration: 2000,
							location: 'middle'
						});
					}
				}
			}
		}
	}

	function checkNet(ip, port, webName) {
		var url = "http://" + ip + ":" + port + "/" + webName + "/autoLoginController!login.m?_u=admin&_p=123456&_pt=min" + "&_to=padController!login.m";
		var params = new Object();
		params.url = url;
		params.method = 'post';
		params.dataType = 'text';
		params.returnAll = 'false';
		params.timeout = 5;

		var data = {
			values: {
				_u: 'admin',
				_p: '123456'
			}
		};

		ajaxForData(params, data, false, function (ret, err) {
			if (ret) {
				api.toast({
					msg: '网络连接正常',
					duration: 2000,
					location: 'middle'
				});
			} else {
				var errobj = eval(err);
				if (errobj.code == 1) {
					api.toast({
						msg: '网络连接超时，请切换网络',
						duration: 2000,
						location: 'middle'
					});
				} else if (errobj.code == 0) {
					api.toast({
						msg: '网络连接失败，请切换网络',
						duration: 2000,
						location: 'middle'
					});
				} else {
					api.toast({
						msg: JSON.stringify(err),
						duration: 5000
					});
				}
			}
		});
	}

	function doSave() {
		var serverIpNO = localStorage.getItem('serverIpN');
		var serverPortNO = localStorage.getItem('serverPortN');
		var serverProjectNO = localStorage.getItem('serverProjectN');
		var serverIpWO = localStorage.getItem('serverIpW');
		var serverPortWO = localStorage.getItem('serverPortW');
		var serverProjectWO = localStorage.getItem('serverProjectW');

		var netRadioObj = document.getElementsByName("netRadio");
		var netRadioStr = "";

		for (j = 0; j < netRadioObj.length; j++) {
			if (netRadioObj[j].checked) {
				netRadioStr = netRadioObj[j].value;
			}
		}

		localStorage.setItem('netChoice', netRadioStr);
		//保存内网配置信息
		var serverIp = $("#serverIp").val();
		var serverPort = $("#serverPort").val();
		var serverProject = $("#serverProject").val();

		localStorage.setItem('serverIpN', serverIp);
		localStorage.setItem('serverPortN', serverPort);
		localStorage.setItem('serverProjectN', serverProject);
		//保存外网配置信息
		serverIp = $("#serverIpW").val();
		serverPort = $("#serverPortW").val();
		serverProject = $("#serverProjectW").val();

		localStorage.setItem('serverIpW', serverIp);
		localStorage.setItem('serverPortW', serverPort);
		localStorage.setItem('serverProjectW', serverProject);

		//设备唯一号
		var equipUniqueId = $("#equipUniqueId").val();
		localStorage.setItem('equipUniqueId', equipUniqueId);

		var clearFlag = 'N';
		//判断网络设置是否修改
		if ($("#serverIp").val() != serverIpNO) clearFlag = 'Y';
		if ($("#serverPort").val() != serverPortNO) clearFlag = 'Y';
		if ($("#serverProject").val() != serverProjectNO) clearFlag = 'Y';
		if ($("#serverIpW").val() != serverIpWO) clearFlag = 'Y';
		if ($("#serverPortW").val() != serverPortWO) clearFlag = 'Y';
		if ($("#serverProjectW").val() != serverProjectWO) clearFlag = 'Y';

		if (clearFlag == 'Y') {
			localStorage.removeItem('workcenterGid');
			localStorage.removeItem('workcenterCode');
			localStorage.removeItem('workcenterName');
		}

		//保存到配置文件
		var ipData = "serverIpN=" + $("#serverIp").val()
			+ ",serverPortN=" + $("#serverPort").val()
			+ ",serverProjectN=" + $("#serverProject").val()
			+ ",serverIpW=" + $("#serverIpW").val()
			+ ",serverPortW=" + $("#serverPortW").val()
			+ ",serverProjectW=" + $("#serverProjectW").val()
			+ ",equipUniqueId=" + $("#equipUniqueId").val();

		console.log("ipData###" + ipData);
		api.writeFile({
			path: 'fs://ipConfig.txt',
			data: ipData
		}, function (ret, err) {
			if (ret.status) {
				console.log("写入数据成功");
				closeWin();
			} else {
				var errMsg = "写入数据失败：" + err.msg + "," + err.code
				console.log(errMsg);
				api.toast({
					msg: errMsg
				});
			}
		});
	}
</script>

</html>